import axios from 'axios'
import mpAdapter from 'axios-miniprogram-adapter'
import {
	netConfig
} from '@/config/net.config.js'

axios.defaults.adapter = mpAdapter
const {
	baseURL,
	contentType,
	requestTimeout,
	successCode
} = netConfig

let tokenLose = true;

// 创建axios实例
const request = axios.create({
	baseURL,
	timeout: requestTimeout,
	headers: {
		'Content-Type': contentType
	}
})

// 请求拦截器
request.interceptors.request.use(
	(config) => {
		// 这是请求拦截器
		return config;
	},
	(error) => {
		return Promise.reject(error)
	}
)

// 响应拦截器
request.interceptors.response.use(
	(response) => {
		const res = response.data
		if (res.status === -1 && tokenLose) {
			tokenLose = false
			uni.showToast({
				title: '服务器异常',
				duration: 2000
			})
			return Promise.reject(res)
		}
		if (successCode.indexOf(res.status) !== -1) {
			return Promise.reject(res)
		}
		return res
	},
	(error) => {
		return Promise.reject(error)
	}
)

export default request